package com.css.zfzx.fwsjcj.modules.taskmanage.task.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.user.repository.UserRepository;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.modules.basecontroller.service.FwDivisionService;
import com.css.zfzx.fwsjcj.modules.quality.vo.QualityVo;
import com.css.zfzx.fwsjcj.modules.structure.entity.FwStructureFormEntity;
import com.css.zfzx.fwsjcj.modules.structure.service.FwStructureFormService;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.entity.FwTaskEntity;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.repository.TaskQueryRepsitory;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.repository.TaskRepository;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.service.TaskService;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.vo.GroupVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.vo.TaskQueryVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.entity.FwFormEntity;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.TaskFromService;
import com.css.zfzx.fwsjcj.modules.user.repository.FwUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    TaskRepository taskRepository;
    @Autowired
    FwUserRepository fwUserRepository;
    @Autowired
    TaskQueryRepsitory taskQueryRepsitory;
    @Autowired
    UserRepository userRepository;
    @Autowired
    FwDivisionService fwDivisionService;
    @Autowired
    FwStructureFormService fwStructureFormService;
    @Autowired
    TaskFromService taskFromService;

    @Override
    public void saveTask(FwTaskEntity taskEntity) {
        String userId = PlatformSessionUtils.getUserId();
        if (!StringUtils.isEmpty(taskEntity.getGroupLeaderId())) {
            String groupLeaderId = taskEntity.getGroupLeaderId();
            UserEntity userEntity = userRepository.findOneByUserId(groupLeaderId);
            taskEntity.setGroupLeaderMobile(userEntity.getMobilePhone());
        }
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        if (StringUtils.isEmpty(taskEntity.getTaskId())) {
            taskEntity.setTaskId(UUIDGenerator.getUUID());
        }
        taskEntity.setDelFlag(Constant.IS_VALID_YES);
        taskEntity.setCreateUser(userId);
        if (StringUtils.isEmpty(taskEntity.getGroupId())) {
            taskEntity.setStatus(Constant.TASK_STATUS_NO);
        } else {
            taskEntity.setStatus(Constant.TASK_STATUS_DONING);
        }
        if (!StringUtils.isEmpty(taskEntity.getDivision())) {
            String division = taskEntity.getDivision();
            String fullNameById = fwDivisionService.findFullNameById(division);
            taskEntity.setDivision(fullNameById);
        }
        taskEntity.setTaskManager(user.getUserName());
        taskEntity.setCreateTime(new Date());
        taskEntity.setCreateUser(userId);
        // 任务质检状态 0未完成审核不能质检
        taskEntity.setQualityStatus("0");
        taskRepository.save(taskEntity);
    }

    @Transactional
    @Override
    public void updateTask(GroupVo groupVo) {
        String groupId = groupVo.getGroupId();
        String id = groupVo.getTaskId();
        String groupLeader = groupVo.getGroupLeader();
        String groupLearderId = groupVo.getGroupLeaderId();
        String groupName = groupVo.getGroupName();
        UserEntity userEntity = userRepository.findOneByUserId(groupLearderId);
        String mobilePhon = userEntity.getMobilePhone();
        taskRepository.updateTask(groupId, id, groupLeader, mobilePhon, groupName, groupLearderId);
    }

    @Transactional
    @Override
    public void deleteTask(List<String> ids) throws Exception{
        //删除任务下关联的表单信息
        //查询任务关联的表单的状态信息
        if(ids.size()>0){
            List<String> formIds = new ArrayList<>();
            List<String> taskIds = new ArrayList<>(ids.size());
            for(String id : ids){
                String taskId = id.split("_")[0];
                taskIds.add(taskId);
                //0是普查 1是详查
                String taskType = id.split("_")[1];
                //如果是普查级联删除fwform中的任务关联的数据，否则删除FwStructureForm中的数据
                if(Constant.TASK_TYPE_PU.equalsIgnoreCase(taskType)){
                    //普查
                    List<FwFormEntity> pcList = taskFromService.findByTaskId(taskId);
                    if(pcList!=null && pcList.size()>0){
                        pcList.forEach(pc->{
                            if(Integer.parseInt(pc.getSpType())>0){
                                throw new RuntimeException("删除失败,存在已提交的表单数据");
                            }
                            formIds.add(pc.getFwId());
                        });
                        taskFromService.deletAll(formIds);
                    }
                }else if(Constant.TASK_TYPE_XC.equalsIgnoreCase(taskType)){
                    List<FwStructureFormEntity> forms = fwStructureFormService.getFormByTaskId(taskId);
                    if(forms.size()>0){
                        for(FwStructureFormEntity entity : forms){
                            if(Integer.parseInt(entity.getStatus())>0){
                                throw new RuntimeException("删除失败,存在已提交的表单数据");
                            }
                            formIds.add(entity.getId());
                        }
                        fwStructureFormService.delete(formIds);
                    }
                }

            }
            if(taskIds!=null && taskIds.size()>0){
                taskRepository.deleteTask(taskIds);
            }

        }


    }

    @Override
    public JSONObject getPage(String type, HttpServletRequest request, TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        Page<FwTaskEntity> page = taskQueryRepsitory.getPage(type, request, taskQueryVo, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    @Override
    public FwTaskEntity findById(String id) {
        FwTaskEntity fwTaskEntity = taskRepository.findById(id).get();
        return fwTaskEntity;
    }
    @Override
    public FwTaskEntity findbyName(String taskName) {
        FwTaskEntity fwTaskEntity = taskRepository.findbyName(taskName);
        return fwTaskEntity;
    }

    @Override
    public JSONObject findPage(String type, int curtPage, int pageSize) {
        Page<FwTaskEntity> page = taskQueryRepsitory.findPage(type, curtPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    @Override
    public List<FwTaskEntity> getAllTask(HttpServletRequest request) {

        List<FwTaskEntity> all = taskRepository.findAllVild();
        return all;
    }

    @Override
    public List<FwTaskEntity> getJGTask(HttpServletRequest request) {
        List<FwTaskEntity> all = taskRepository.findJGVild();
        return all;
    }

    @Transactional
    @Override
    public void completeTask(String type, String taskId) {
        // 任务完成后，并且修改质检状态为1：可以发配质检员
        String qualityStatus = "1";
        taskRepository.completeTask(type, qualityStatus, taskId);
    }

    @Override
    public List<FwTaskEntity> findByIds(List<String> list) {
        List<FwTaskEntity> allById = taskRepository.findAllById(list);
        return allById;
    }

    @Override
    public JSONObject getPage(TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        Page<FwTaskEntity> page = taskQueryRepsitory.getPage(taskQueryVo, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    @Override
    public void sendQualityInspector(QualityVo qualityVo) {
        FwTaskEntity taskEntity = taskRepository.findById(qualityVo.getTaskId()).get();
        // 设置质检人id和名称
        taskEntity.setQualityId(qualityVo.getQualityId());
        taskEntity.setQualityName(qualityVo.getQualityName());
        // 设置质检状态2：质检中(即已经分配质检人)
        taskEntity.setQualityStatus(Constant.TASK_QUALITY_STATUS_ING);
        taskRepository.save(taskEntity);
    }

    @Override
    public JSONObject getPageByUser(TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        Page<FwTaskEntity> page = taskQueryRepsitory.getPageByUser(taskQueryVo, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    @Override
    public void update(FwTaskEntity taskEntity) {
        if (StringUtils.isEmpty(taskEntity.getTaskId())){
            throw new RuntimeException("修改主键ID不能为空");
        }
        taskRepository.save(taskEntity);
    }

    @Override
    public JSONObject getPageTask(String type, HttpServletRequest request, TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        Page<FwTaskEntity> page = taskQueryRepsitory.getPageTask(type,request,taskQueryVo,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }


}
